package niuke;

import leetcode.LinkedList.ListNode;

/**
 * @author wangmaolin1
 * @date 2022/7/27 11:30 下午
 */
public class _78反转链表 {

    public static ListNode ReverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode res = new ListNode(-1);
        ListNode temp = head;
        ListNode next = head.next;
        while (temp != null) {
            if (res.next == null) {
                res.next = temp;
                temp.next = null;
            } else {
                temp.next = res.next;
                res.next = temp;
            }
            temp = next;
            if (next != null) {
                next = next.next;
            }
        }
        return res.next;


    }

    public static ListNode ReverseList2(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode cur= head;
        ListNode pre = null;
        while (cur!=null){
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        return pre;

    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        System.out.println(ReverseList2(head));
    }

}
